<template>
    <div class="shujuyuan-config-container">
        <el-button @click="dialogVisible=true">自定义SQL</el-button>
        <ShujuyuanComConfig v-if="editSourseVisible" @save="_saveEchartConfig" @open="_selectZidian" :form="form" :echat-form="echatForm" :glzd-options="glzdOptions" :data-sourse-id="dataSourseId"/>
        <el-dialog
            title="数据源配置"
            :visible.sync="dialogVisible"
            width="80%"
            @close="_closeClick"
            >
            <el-form label-width="70px" :inline="true" class="set-box" label-position="left">
                <div class="set-item">
                    <h3>基础信息</h3>
                    <div class="head">
                        <el-form-item label="源编码" class="mr30">
                            <el-input v-model="form.datasourseCode"></el-input>
                        </el-form-item>
                        <el-form-item label="源名称" class="mr30">
                            <el-input v-model="form.datasourseName"></el-input>
                        </el-form-item>
                        <el-form-item label="开启缓存" class="mr30">
                            <el-radio-group v-model="form.isRedis">
                                <el-radio label="y">是</el-radio>
                                <el-radio label="n">否</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="图表类型" class="mr30">
                            <el-select v-model="form.echartType" placeholder="请选择">
                                <el-option
                                    v-for="item in echartTypeData"
                                    :key="item.value"
                                    :label="item.name"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                </div>
                <div class="set-item clearfix">
                    <h3>自定义SQL</h3>
                    <div class="tree-box">
                        <h3 class="title">实体树</h3>
                        <div class="tree">
                            <el-input
                            placeholder="Search..."
                            v-model="filterText">
                                <el-button slot="append" icon="el-icon-search"></el-button>
                            </el-input>
                            <el-tree
                            class="filter-tree"
                            :data="zTreeData"
                            :props="defaultProps"
                            node-key="id" 
                            @node-click="nodeClick"
                            @node-expand="nodeExpand"
                            :filter-node-method="filterNode"
                            ref="tree">
                            </el-tree>
                        </div>
                    </div>
                    <div class="sql-box">
                        <el-button type="primary" @click="_saveSqlClick">保存SQL</el-button>
                        <el-button type="success">转换SQL</el-button>
                        <el-button type="danger">清空</el-button>
                        <el-button type="warning" @click="_yingSheClick">映射</el-button>
                        <el-input
                            class="textarea"
                            type="textarea"
                            resize="none"
                            clearable
                            :rows="15"
                            placeholder="请输入内容"
                            v-model="form.entitySql">
                        </el-input>
                    </div>
                    <div class="echart-box">
                        <h3 class="title">图例配置</h3>
                        <ShujuyuanComConfig @save="_saveEchartConfig" @open="_selectZidian" :form="form" :echat-form="echatForm" :glzd-options="glzdOptions" :data-sourse-id="dataSourseId"/>
                    </div>
                </div>
            </el-form>
            <el-dialog
                width="70%"
                title="表单字典选择"
                :visible.sync="innerVisible"
                append-to-body>
                <el-input
                    style="width: 400px;"
                    placeholder="字典编码，字典名称"
                    v-model="findDictForm.condition">
                        <el-button slot="append" icon="el-icon-search"></el-button>
                </el-input>
                <el-table
                    ref="dictTable"
                    :data="tableData"
                    highlight-current-row
                    @current-change="setCurrent"
                    style="width: 100%">
                    <el-table-column
                    property="dictTypeCode"
                    label="字典类编码"
                    >
                    </el-table-column>
                    <el-table-column
                    property="dictTypeName"
                    label="字典类名称"
                    >
                    </el-table-column>
                    <el-table-column
                    property="dictTypeClass"
                    label="字典类分类">
                    </el-table-column>
                    <el-table-column
                    property="dictTypeRemark"
                    label="字典类描述">
                    </el-table-column>
                </el-table>
                <el-pagination
                    class="mt10"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="findDictForm.offset"
                    :page-sizes="[5, 10, 15, 20]"
                    :page-size="findDictForm.limit"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="DictTotal">
                </el-pagination>
            </el-dialog>
            <span slot="footer" class="dialog-footer">
                <el-button @click="_closeClick">关 闭</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { getEchartSelectFullTree, saveDatasource, mappingSourceColumn, getSourceSelect, findDictList, saveEchartConfig, loadDataSourceInfo, loadechartsforSourcefo } from '@/api/api'
import { mapGetters, mapActions } from 'vuex'
import ShujuyuanComConfig from './ShujuyuanComConfig'
const comData = {
    XColumnDiv: {
        id:"",
        paramCode: "XColumnDiv", //圖例关联字段
        paramValue: ''  
    }, XDataFrom: {
        id: "",
        paramCode: "XDataFrom", // 圖例来源方式:                        
        paramValue: ''   
    }, XColumn: {
        id: "",
        paramCode: "XColumn",//圖例关联字段
        paramValue: ''   
    }, Xconfig_code:{
        id: "",
        paramCode: "Xconfig_code", //圖例字段关联字典编码
        paramValue: ''   
    }, Xconfig_name: {
        id: "",
        paramCode: "Xconfig_name", //圖例字段关联字典名称
        paramValue: ''   
    }, YDataValueFrom: {
        id: "",
        paramCode: "YDataValueFrom",// 数据来源方式
        paramValue: ''  
    }, Xconfig_type: {
        id: "",
        paramCode: "Xconfig_type",  // 圖例字段关联字典数量
        paramValue: ''   
    }, type:{
        id: "",
        paramCode: "type",    //图表类型
        paramValue: ""
    }
}
const barData = {
    ...comData,
    YColumnDiv:{
        "id": "",
        "paramCode": "YColumnDiv",     // y轴关联字段
        "paramValue": ""
    }, YDataValueFrom: {
        "id": "",
        "paramCode": "YDataValueFrom",   //y轴数据来源方式:
        "paramValue": "1"
    }, YDataFrom: {
        "id": "",
        "paramCode": "YDataFrom",   // y轴图块来源方式:
        "paramValue": "1"
    }, YColumn: {
        "id": "",
        "paramCode": "YColumn", // y轴字段关联字典
        "paramValue": ""
    }, YGroupColumn: {
        "id": "",
        "paramCode": "YGroupColumn",
        "paramValue": ""
    }, Yconfig_name:{
        "id": "",
        "paramCode": "Yconfig_name", //y轴字段关联字典
        "paramValue": ""
    }, Yconfig_code:{
        "id": "",
        "paramCode": "Yconfig_code", //y轴字段关联字典编码
        "paramValue": "emp_SEX"
    }, Yconfig_type:{
        "id": "",
        "paramCode": "Yconfig_type",//y轴字段关联字典数量
        "paramValue": ""
    }, YColumnForV: {
        "id": "",
        "paramCode": "YColumnForV",   //y轴数据关联字段
        "paramValue": ""
    }, sql:{
        "id": "",
        "paramCode": "sql",
        "paramValue": ""
    }
}
const pieData = comData
const loudouComData = {
    XDataFrom: {
        id: "",
        paramCode: "XDataFrom", // 圖例来源方式:                        
        paramValue: ''   
    }, XColumn: {
        id: "",
        paramCode: "XColumn",//圖例关联字段
        paramValue: ''   
    }, Xconfig_code:{
        id: "",
        paramCode: "Xconfig_code", //圖例字段关联字典编码
        paramValue: ''   
    }, Xconfig_name: {
        id: "",
        paramCode: "Xconfig_name", //圖例字段关联字典名称
        paramValue: ''   
    }, YDataValueFrom: {
        id: "",
        paramCode: "YDataValueFrom",// 数据来源方式
        paramValue: ''  
    }, Xconfig_type: {
        id: "",
        paramCode: "Xconfig_type",  // 圖例字段关联字典数量
        paramValue: ''   
    }, type:{
        id: "",
        paramCode: "type",    //图表类型
        paramValue: ""
    }
}
const loudouData =  {
    ...loudouComData
    ,loudousql:{
        id: "",
        paramCode: "loudousql",
        paramValue: ""
	}
}
const gaugeData = {
    XDataFrom: {
        id: "",
        paramCode: "XDataFrom", // 圖例来源方式:                        
        paramValue: ''   
    }, XColumn: {
        id: "",
        paramCode: "XColumn",//圖例关联字段
        paramValue: ''   
    },YDataValueFrom: {
        id: "",
        paramCode: "YDataValueFrom",// 数据来源方式
        paramValue: ''  
    },
    ResultColumnDiv: {
        id: "",
        paramCode: "ResultColumnDiv",    //圖例目标字段
        paramValue: ""
    },
    type: {
        id: "",
        paramCode: "type",   
        paramValue: ""
    },yibiaosql: {
        id: "",
        paramCode: "yibiaosql", 
        paramValue: ""
    }
}
const radarData = {
    XDataFrom: {
        id: "",
        paramCode: "XDataFrom", // 圖例来源方式:                        
        paramValue: ''   
    }, XColumn: {
        id: "",
        paramCode: "XColumn",//圖例关联字段
        paramValue: ''   
    }, Xconfig_code:{
        id: "",
        paramCode: "Xconfig_code", //圖例字段关联字典编码
        paramValue: ''   
    }, Xconfig_name: {
        id: "",
        paramCode: "Xconfig_name", //圖例字段关联字典名称
        paramValue: ''   
    }, YColumn: {
        id: "",
        paramCode: "YColumn",// 数据来源方式
        paramValue: ''  
    }, Xconfig_type: {
        id: "",
        paramCode: "Xconfig_type",  // 圖例字段关联字典数量
        paramValue: ''   
    }, type:{
        id: "",
        paramCode: "type",    //图表类型
        paramValue: ""
    }, maxvalue: {
        id: '',
        paramCode: "maxvalue",	//设置纬度最大值
        paramValue: 10
    }, sql:{
        id: '',
        paramCode: "sql",
        paramValue: ""
    }
}
const tupuData =  {
    dataway: {
        "id": '',
        "paramCode": "dataway",
        "paramValue": ""
    }, treeid: {
        "id": '',
        "paramCode": "treeid",
        "paramValue": ""
    }, DataId: {
        "id": '',
        "paramCode": "DataId",
        "paramValue": ""
    }, DataName: {
        "id": '',
        "paramCode": "DataName",
        "paramValue": ""
    }, DataPid: {
        "id": '',
        "paramCode": "DataPid",
        "paramValue": ""
    }, Datavalue: {
        "id": '',
        "paramCode": "Datavalue",
        "paramValue": ""
    }, type: {
        "id": '',
        "paramCode": "type",
        "paramValue": ""
    }, maxLevel: {
        "id": '',
        "paramCode": "maxLevel",
        "paramValue": ""
    }
}
const quanData = {
    ...loudouComData
    ,quansql:{
        id: "",
        paramCode: "quansql",
        paramValue: ""
	}
}
const wordCloudData = {
    ...loudouComData
    ,wordsql:{
        id: "",
        paramCode: "wordsql",
        paramValue: ""
	}
}
export default {
    props: ['data'],
    components: {
        ShujuyuanComConfig
    },
    data() {
        return {
            sqlText: '',
            dialogVisible: false,
            innerVisible: false,
            findDictForm: {
                offset: 1,
                limit: 10,
                condition: ''
            },
            selectZidianType: 'x',
            dataSourseId: '',
            DictTotal: 0,
            tableData: [],
            form: {
                id: '',
                echartType: '',
                datasourseName: '',
                datasourseCode: '',
                isRedis: 'n',
                entitySql: '',
                defSql: ''
            },
            echatForm: {},
            filterText: '',
            zTreeData: [],
            defaultProps: {
                children: 'children',
                label: 'name'
            },
            glzdOptions: [],
            echartTypeData: [
                {name: '饼图',value: 'pie'},
                {name: '柱状图',value: 'bar'},
                {name: '漏斗图',value: 'loudou'},
                {name: '圈图',value: 'quan'},
                {name: '词云图',value: 'wordCloud'},
                {name: '仪表盘',value: 'gauge'},
                {name: '雷达图', value: 'Radar'},
                {name: '旭日图', value: 'tupu'},
                {name: '机构图', value: 'tree'},
            ],
            sqlText: ''
        }
    },
    computed: {
		...mapGetters(['addSourseVisible','editSourseVisible','editSuccess']),
	},
    watch: {
        filterText(val) {
            this.$refs.tree.filter(val);
        },
        sqlText(val) {
            this.form.entitySql = this.form.entitySql+val
        },
        'findDictForm.condition'(val){
            this._findDictList()
        },
        editSourseVisible(val){
            if(val) {
                this.form.id = this.data.options.sourceId
                this.dataSourseId = this.data.options.sourceId
                this._loadDataSourceInfo(this.data.options.sourceId)
                this._getSourceSelect()
            }
        },
        'form.echartType'(val){
            this.echartTypeChange()
        },
        addSourseVisible(val) {
            if(val) {
                this.dialogVisible = true
                this.form = {
                    id: '',
                    echartType: '',
                    datasourseName: '',
                    datasourseCode: '',
                    isRedis: 'n',
                    entitySql: '',
                    defSql: ''
                }
                this.glzdOptions = []
            } else {
                this.dialogVisible = false
            }
            
        }
    },
    created(){
        this._getEchartSelectFullTree();
        if(this.editSourseVisible) {
            this.form.id = this.data.options.sourceId
            this.dataSourseId = this.data.options.sourceId
            this._loadDataSourceInfo(this.data.options.sourceId)
            this._getSourceSelect()
            this.echartTypeChange()
        }
    },
    methods: {
        ...mapActions([
            'addSourseVisibleChange',
            'editSourseVisibleChange',
            'editSuccessChange'
        ]),
        echartTypeChange(){
            switch(this.form.echartType) {
                case 'pie':
                    this.echatForm = pieData
                    break;
                case 'bar':
                    this.echatForm = barData
                    break;
                case 'loudou':
                    this.echatForm = loudouData
                    break;
                case 'quan':
                    this.echatForm = quanData
                    break;
                case 'wordCloud':
                    this.echatForm = wordCloudData
                    break;
                case 'gauge':
                    this.echatForm = gaugeData
                    break;
                case 'Radar':
                    this.echatForm = radarData
                    break;
                case 'tupu':
                    this.echatForm = tupuData
                    break;
                case 'tree':
                    this.echatForm = tupuData
                    break;
                default:
                    this.echatForm = pieData
            } 
            return this.echatForm
        },
        _closeClick(){
            this.dialogVisible = false
            this.addSourseVisibleChange(false)
            this.editSourseVisibleChange(false)
        },
        // 数据源查询回显
        _loadDataSourceInfo(id){
            loadDataSourceInfo({dataSourseId: id}).then(res=>{
                if(res.rcode=='0000') {
                    this._loadechartsforSourcefo({id: id,echartType: res.data.echartType})
                    this.form = res.data
                }
            })
        },
        _loadechartsforSourcefo(param){
            loadechartsforSourcefo({dataSourseId: param.id,echartType: param.echartType}).then(res=>{
                if(res.rcode=='0000') {
                    const resData = res.data;
                    for(const item in this.echatForm){
                        this.echatForm[item].id = resData[item].id
                        this.echatForm[item].paramValue = resData[item].paramValue
                    }
                }
            })
        },
        // 选中的字典
        setCurrent(row) {
            console.log(row)
            if(row) {
                if(this.selectZidianType==='y') {
                    this.$refs.dictTable.setCurrentRow(row);
                    this.echatForm.Yconfig_name.paramValue = row.dictTypeName
                    this.echatForm.Yconfig_type.paramValue = row.dictTypeClass
                    this.echatForm.Yconfig_code.paramValue = row.dictTypeCode
                    this.innerVisible = false
                } else {
                    this.$refs.dictTable.setCurrentRow(row);
                    this.echatForm.Xconfig_name.paramValue = row.dictTypeName
                    this.echatForm.Xconfig_type.paramValue = row.dictTypeClass
                    this.echatForm.Xconfig_code.paramValue = row.dictTypeCode
                    this.innerVisible = false
                }
                
            }
            
        },
        handleSizeChange(val) {
            this.findDictForm.limit = val
            this._findDictList()
        },
        handleCurrentChange(val) {
            this.findDictForm.offset = val
            this._findDictList()
        },
        filterNode(value, data) {
            if (!value) return true;
            return data.name.indexOf(value) !== -1;
        },
        nodeClick(val,fnode){
            if(val.realCode=='2'){
                this.sqlText = ' ['+val.name+']'
            }
            if(!val.isParent){
                const fname = fnode.parent.data.name
                const cname = val.name
                this.sqlText= ' ['+fname+'.'+cname+']'
            }
        },
        nodeExpand(val) {
            if(val.isParent&&val.children[0].name=='') {
                getEchartSelectFullTree({id: val.id,lv:val.realCode,n: val.name}).then(res=>{
                    val.children = []
                    this.$refs.tree.updateKeyChildren(val.id,res)
                })
            }
        },
        _getEchartSelectFullTree(){
            getEchartSelectFullTree({}).then(res=>{
                this.zTreeData = this.optionData(res)
            })
        },
        _getSourceSelect(){
            getSourceSelect(this.dataSourseId).then(res=>{
                if(res.rcode=='0000') {
                    this.glzdOptions = res.data
                } else {
                    this.$message({
                        message: res.desc,
                        type: 'warning'
                    });
                }
            })
        },
        _findDictList(){
            findDictList(this.findDictForm).then(res=>{
                if(res.rcode=='0000') {
                    this.tableData = res.data.rows
                    this.DictTotal = res.data.total
                } else {
                    this.$message({
                        message: res.desc,
                        type: 'warning'
                    });
                }
                
            })
        },
        _selectZidian(type){
            this.selectZidianType = type
            this.innerVisible = true
            this._findDictList()
        },
        optionData(data) {
            let cloneData = JSON.parse(JSON.stringify(data)); // 对源数据深度克隆
            return cloneData.filter(father => { // 循环所有项，并添加children属性
                if(father.isParent==true) {
                    father.children = [{name: '',label: ''}]
                }
                let branchArr = cloneData.filter(child => father.id == child.pId); // 返回每一项的子级数组
                branchArr.length > 0 ? father.children = branchArr : ''; //给父级添加一个children属性，并赋值
                return father.pId == 0; //返回第一层
            });
        }, //将查询到的list转为树形

        // 保存SQL
        _saveSqlClick(){
            saveDatasource(this.form).then(res=>{
                if(res.rcode=='0000'){
                    this.$message({
                        message: '保存SQL成功',
                        type: 'success'
                    });
                    this.dataSourseId = res.data.id
                    this.form.id = res.data.id
                    this.form.defSql = res.data.defSql
                } else {
                    this.$message({
                        message: res.desc,
                        type: 'warning'
                    });
                }
            })
        },
        // 映射SQL
        _yingSheClick(){
            const form = {
                dataSourseId: this.dataSourseId,
                entitySql: this.form.entitySql
            }
            mappingSourceColumn(form).then(res=>{
                if(res.rcode=='0000'){
                    this.$message({
                        message: '映射成功',
                        type: 'success'
                    });
                    this._getSourceSelect()
                } else {
                    this.$message({
                        message: res.desc,
                        type: 'warning'
                    });
                }
            })
        },
        // 保存echart配置
        _saveEchartConfig(){
            this.dialogVisible = false
        }
    }
}
</script>
<style lang="scss" scoped>
    .widget-config-container .config-content{
        .el-dialog__body{
            padding: 15px 20px;
        }
        .shujuyuan-config-container{
            .head{
                margin-left: 20px;
            }
            .el-form-item{
                border: none;
                padding: 0;
                .el-input,.el-select{
                    width: 240px;
                }
            }
            .mt10{
                margin-top: 10px;
            }
            .mr30{
                margin-right: 50px;
            }
            .set-item{
                >h3{
                    color: #333;
                    font-size: 18px;
                    padding: 10px 15px;
                    border-left: 5px solid #409EFF;
                    margin-bottom: 10px;
                }
                .tree-box,.echart-box{
                    border: 1px solid #409EFF;
                    border-radius: 5px;
                    .title{
                        background: #409EFF;
                        padding: 15px 10px;
                        color: #fff;
                        font-size: 14px;
                    }
                    .tree{
                        padding: 10px;
                        overflow-x: hidden;
                        .el-tree{
                            height: 500px;
                            margin-top: 5px;
                            overflow-y: auto;
                            overflow-x: hidden;
                        }
                    }
                    width: 400px;
                    float: left;
                }
                .tree-box,.echart-box,.sql-box{
                    height: 600px;
                }
                .echart-box{
                    width: 400px;
                    margin-left: 10px;
                    .echart{
                        height: 550px;
                        overflow: auto;
                        padding: 10px 20px;
                    }
                }
                .sql-box{
                    width: calc(100% - 820px);
                    float: left;
                    margin-left: 10px;
                    .textarea{
                        margin-top: 15px;
                    }
                }
            }
        }
    }
    
</style>